import { createRouter, createWebHistory } from 'vue-router'

// 路由配置
const routes = [
  {
    path: '/',
    name: 'Home',
    redirect: '/login',
    meta: { requiresAuth: false }
  },
  {
    path: '/home',
    name: 'HomePage',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('../views/Profile.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: () => import('../views/Favorites.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/warnings',
    name: 'Warnings',
    component: () => import('../views/WarningPage.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/forecast/:city/:province',
    name: 'ForecastDetail',
    component: () => import('../views/ForecastDetail.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/icons',
    name: 'WeatherIcons',
    component: () => import('../views/WeatherIconsDemo.vue'),
    meta: { requiresAuth: false }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue')
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('weatherAppUser')
  
  // 检查路由是否需要认证
  if (to.meta.requiresAuth && !isAuthenticated) {
    // 如果需要认证但用户未登录，重定向到登录页面
    next({ name: 'Login', query: { redirect: to.fullPath } })
  } else {
    // 其他情况正常导航
    next()
  }
})

export default router 